package com.dhecp.project.business.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.mapper.OperateCompanyApplyMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.IpUtils;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.FbaPlanOrder;
import com.dhecp.project.business.domain.FbaPlanOrderDetail;
import com.dhecp.project.business.domain.FbaProductActive;
import com.dhecp.project.business.mapper.FbaPlanOrderDetailMapper;
import com.dhecp.project.business.mapper.FbaPlanOrderMapper;
import com.dhecp.project.business.service.FbaPlanOrderService;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.AccountCountForCompany;
import com.dhecp.project.finance.mapper.AccountCountForCompanyMapper;
import com.dhecp.project.flowable.mapper.SysProcessInstanceMapper;
import com.dhecp.project.flowable.service.ActProcessService;
import com.dhecp.project.hr.domain.AmazonShop;
import com.dhecp.project.hr.mapper.AmazonShopMapper;
import com.dhecp.project.logstics.domain.FbaBox;
import com.dhecp.project.logstics.mapper.FbaBoxMapper;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.domain.StockControlRunning;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.storage.mapper.StockControlRunningMapper;
import com.dhecp.project.storage.service.StockControlService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 头程计划单 服务层
 * @Author fxz
 * @Date 2022/9/23
 */
@Service
public class FbaPlanOrderServicelmpl extends BaseModuleServiceImpl implements FbaPlanOrderService {


    @Autowired
    private FbaPlanOrderMapper fbaPlanOrderMapper;
    @Autowired
    private FbaPlanOrderDetailMapper fbaPlanOrderDetailMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;

    @Autowired
    private FbaBoxMapper fbaBoxMapper;

    private String moduleTable = ModuleTable.FBA_BOX;
    private String moduleTable1 = ModuleTable.FBA_PLAN_ORDER;

    @Autowired
    private StockControlService stockControlService;

    @Autowired
    private StockControlMapper storageMapper;

    @Autowired
    private UpdateLogService updateLogService;

    @Autowired
    private AccountCountForCompanyMapper accountCountForCompanyMapper;

    @Autowired
    private AmazonShopMapper amazonShopMapper;

    @Autowired
    private ActProcessService actProcessService;

    @Autowired
    private SysProcessInstanceMapper processInstanceMapper;

    @Autowired
    private StockControlRunningMapper stockControlRunningMapper;

    @Autowired
    private OperateCompanyApplyMapper operateCompanyApplyMapper;


    /**
     * 查询头程计划单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<FbaPlanOrder> queryList(Map<String, Object> params) throws Exception {
        //特殊字段商品编码修改查询详情有关联的数据
        if (params.get("commodityCode") != null && !params.get("commodityCode").equals("")){
            params.put("commodityCode1",params.get("commodityCode"));
            params.put("commodityCode","");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句

        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句


        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.createTime DESC";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }

        return fbaPlanOrderMapper.select(params);
    }


    /**
     * 查询头程计划单
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<FbaPlanOrderDetail> querySonList(Map<String, Object> params) {
        return fbaPlanOrderDetailMapper.queryList(params);
    }


    /**
     * 查询列表（头程计划单详情）
     */
    @Override
    public List<FbaPlanOrderDetail> queryFbaPlanOrderDetailByCode(String code) {
        return fbaPlanOrderDetailMapper.queryListByCode(code);
    }


    /**
     * 查询头程计划单详情
     */
    @Override
    public FbaPlanOrderDetail queryFbaPlanOrderDetailByGuid(String guid) {
        return fbaPlanOrderDetailMapper.queryByGuid(guid);
    }


    /**
     * 新增头程计划单
     * @param params
     * @return
     */
    @Override
    public AjaxResult insertFbaPlanOrder(Map<String, Object> params) {
        if (StringUtils.isEmpty(params)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }

        FbaPlanOrder entity = JSON.parseObject(JSON.toJSONString(params), FbaPlanOrder.class);
        entity.setGuid(RandomValueUtils.getGUID());
        entity.setCreateUser(ShiroUtils.getUserId());
        entity.setCreateTime(new Date());
        entity.setUpdateUser(ShiroUtils.getUserId());
        entity.setUpdateTime(new Date());
        if (entity.getGuid() == null || "".equals(entity.getGuid())){
            entity.setGuid(RandomValueUtils.getGUID());
        }

        if (entity.getCode() == null || entity.getCode().length() == 0) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }

        fbaPlanOrderMapper.insertFbaPlanOrder(entity);
        return AjaxResult.success("操作成功");
    }

    @Override
    public FbaPlanOrder queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return fbaPlanOrderMapper.selectFirstRecordByNid(params);
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new FbaPlanOrder());
//        params.put("isAuto", false);
        String guidFind = JSON.parseObject(params.get("infoMap").toString()).getString("guid");
        FbaPlanOrder fbaPlanOrder1 = JSON.parseObject(params.get("infoMap").toString(), FbaPlanOrder.class);
        FbaPlanOrder fbaPlanOrder12 = null;
        if (guidFind != null && !guidFind.equals("")){
            fbaPlanOrder12 = fbaPlanOrderMapper.queryFirstByGuid(guidFind);
            if (fbaPlanOrder12 == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("头程计划不存在,请核实后在操作!");
            }else {
                if (fbaPlanOrder12.getEffectStock() == true){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("头程计划已流转,不允许操作保存,请核实后在操作!");
                }
            }
        }

        //查询网店信息
        AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaPlanOrder1.getSellerId());

        if (amazonShop == null ){
            return AjaxResult.error("网店信息未维护!");
        }
        if (amazonShop.getPhone() == null || amazonShop.getPhone().equals("")){
            return AjaxResult.error("网店信息电话未维护!");
        }
        if (amazonShop.getName() == null || amazonShop.getAddressLine1() == null ||  amazonShop.getCity() == null ||
                amazonShop.getStateOrProvinceCode() == null|| amazonShop.getPostalCode() == null
                || amazonShop.getName().equals("")|| amazonShop.getAddressLine1().equals("")|| amazonShop.getCity().equals("")
                || amazonShop.getStateOrProvinceCode().equals("")|| amazonShop.getPostalCode().equals("")){
            return AjaxResult.error("网店信息发货地址未维护!");
        }

        //账户资金+负载额度+5000< 头程物流费用
        AccountCountForCompany accountCountForCompany = accountCountForCompanyMapper.queryFirstByVGsBm(fbaPlanOrder1.getCodeCompany());
        if (accountCountForCompany.getfJe() +  accountCountForCompany.getfFzEd() + 5000 < Double.valueOf(String.valueOf(fbaPlanOrder1.getPriceTranPredict()))){
            return AjaxResult.error("资金不足,请核实后再操作!");
        }
        //查询运营公司备案
        OperateCompanyApply drOperateCompanyApply = operateCompanyApplyMapper.findVGsBm(fbaPlanOrder1.getCodeCompany());
        if (drOperateCompanyApply.getvGsSh() == null ||drOperateCompanyApply.getvGsSh().equals("")){
            throw new RuntimeException("公司名称和税号不能为空，请维护!");
        }

        AjaxResult ajaxResult = this.saveDataBase(params);

        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        String resNid = infoMap.get("nid").toString();

        FbaPlanOrder fbaPlanOrder = JSON.parseObject(params.get("infoMap").toString(), FbaPlanOrder.class);
        List<FbaPlanOrderDetail> onSonData = new ArrayList<>();
        if (params.containsKey("sonData")){
            onSonData = JSON.parseArray(params.get("infoItems").toString(), FbaPlanOrderDetail.class);
        }

        List<RecordCheck> guidMapList = fbaPlanOrderMapper.findRecords(resNid);

        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()){
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList){
                if (recordCheck != null && recordCheck.getGuid() != null){
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }
        if (onSonData == null || onSonData.size() == 0){
            resNid = "0";
        }else{
            resNid = infoMap.get("nid").toString();
            String guid = "";
            if (fbaPlanOrder.getGuid() == null){
                guid = RandomValueUtils.getGUID();
                fbaPlanOrder.setGuid(guid);
            }else{
                guid = fbaPlanOrder.getGuid().toString();
            }

            for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                Object fieldValue = infoMap.get(field);
                ReflectUtils.setValue(fbaPlanOrder, field, fieldValue);
            }

            if (guidMap.get(guid) == null){
                fbaPlanOrder.setCode(fbaPlanOrder.getBid());
                fbaPlanOrder.setState("0");
                fbaPlanOrder.setDeleted(false);
                fbaPlanOrder.setCreateUser(ShiroUtils.getMandatorId());
                fbaPlanOrder.setStateShareTicketName(fbaPlanOrder.getStateShareTicket()==0?"否":"是");
                fbaPlanOrder.setStateName("制单环节");
                fbaPlanOrderMapper.insertFbaPlanOrder(fbaPlanOrder);
            }else{
                fbaPlanOrder.setStateShareTicketName(fbaPlanOrder.getStateShareTicket()==0?"否":"是");
                fbaPlanOrder.setStateName("制单环节");
                fbaPlanOrderMapper.updateByGuid(fbaPlanOrder);
                guidMap.remove(guid);
            }
            List<FbaPlanOrderDetail> lodData = fbaPlanOrderDetailMapper.queryListCode(fbaPlanOrder.getCode());


            for (FbaPlanOrderDetail item : onSonData
            ) {
                if (fbaPlanOrder.getCreationMethod().equals("自动")){
                    if (item.getPrepInstructionList() == null || item.getPrepInstructionList().equals("")){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("商品包装要求未维护,请前往网店商品信息手动刷新后再操作!");
                    }
                }
                if (item.getGuid() != null){
                    List<FbaPlanOrderDetail> productInfoList = lodData.stream().filter(fbaPlanOrderDetail -> fbaPlanOrderDetail.getGuid().equals(item.getGuid())).collect(Collectors.toList());
                    if (productInfoList.size() != 0){
                        updateNum(fbaPlanOrder,productInfoList.get(0),params,1);
                    }
                    fbaPlanOrderDetailMapper.updateByGuid(item);
                } else {
                    item.setGuid(RandomValueUtils.getGUID());
                    item.setCreateTime(new Date());
                    item.setCodePlanOrder(fbaPlanOrder.getCode());
                    fbaPlanOrderDetailMapper.insertFbaPlanOrderDetail(item);
                }
                //根据详情修改库存的减少可用数量
                updateNum(fbaPlanOrder,item,params,0);
            }

            for (FbaPlanOrderDetail item : lodData
            ) {
                //是否删除
                List<FbaPlanOrderDetail> productInfoList = onSonData.stream().filter(fbaPlanOrderDetail -> fbaPlanOrderDetail.getGuid().equals(item.getGuid())).collect(Collectors.toList());
                if (productInfoList.size() == 0){
                    fbaPlanOrderDetailMapper.delete(item);
                    updateNum(fbaPlanOrder,item,params,1);
                }
            }

        }


        if (!guidMap.isEmpty()){
            for (String guid : guidMap.keySet()){
                List<FbaPlanOrderDetail> lodData = fbaPlanOrderDetailMapper.queryListCode(fbaPlanOrder.getCode());
                if (lodData.size()>0){
                    for (FbaPlanOrderDetail item : lodData
                    ) {
                        //根据详情库存的回填可用数量
                        updateNum(fbaPlanOrder,item,params,1);
                    }
                }
                fbaPlanOrderDetailMapper.deleteCodePlanOrder(fbaPlanOrder.getCode());
                fbaPlanOrderMapper.delete(guid);
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }

    /**
     *@Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<FbaPlanOrder> businessDataList = fbaPlanOrderMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "go");
        }
        for (FbaPlanOrder businessData : businessDataList) {
            Map<String, Object> params3 = new HashMap<String, Object>();
            params3.put("code",businessData.getCode());
            params3.put("moduleTable", moduleTable);
            List<FbaPlanOrderDetail> fbaPlanOrderDetailList = querySonList(params3);
            for (FbaPlanOrderDetail fbaPlanOrderDetail : fbaPlanOrderDetailList){
                if(fbaPlanOrderDetail.getIsSign() != null){
                    if("是".equals(fbaPlanOrderDetail.getIsSign())){
                        if ("无附件".equals(fbaPlanOrderDetail.getvDFilesDefault())){
                            return AjaxResult.error("商品编码:"+fbaPlanOrderDetail.getCommodityCode()+",未上传透明标,请核实后再操作!");
                        }
                    }
                }
            }
        }



        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (FbaPlanOrder businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            fbaPlanOrderMapper.updateFlow(updateFlow);
        }

            return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     *@Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<FbaPlanOrder> businessDataList = fbaPlanOrderMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (FbaPlanOrder businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            fbaPlanOrderMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * 删除头程计划数据
     * @param
     * @return
     * @author DH-Xxj
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult delete(Map<String, Object> params) {
        List<FbaPlanOrder> fbaPlanOrderList = JSON.parseArray(params.get("infoItems").toString(), FbaPlanOrder.class);
        if (fbaPlanOrderList == null || fbaPlanOrderList.size() == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("数据异常!");
        }
        AccountCountForCompany accountCountForCompany;
        for (FbaPlanOrder fbaPlanOrder : fbaPlanOrderList) {
            FbaPlanOrder fbaPlanOrder1 = fbaPlanOrderMapper.queryFirstByGuid(fbaPlanOrder.getGuid());
            if (fbaPlanOrder1 == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("头程计划不存在,请核实后在操作!");
            }


            List<FbaPlanOrderDetail> lodData = fbaPlanOrderDetailMapper.queryListCode(fbaPlanOrder.getCode());
            if (lodData.size()>0){
                for (FbaPlanOrderDetail item : lodData
                ) {
                    //根据详情库存的回填可用数量
                    updateNum(fbaPlanOrder,item,params,1);
                }
            }
            fbaPlanOrderDetailMapper.deleteCodePlanOrder(fbaPlanOrder.getCode());
            fbaPlanOrderMapper.delete(fbaPlanOrder);

            String procInstId = fbaPlanOrder.getProcInstId();
            if (procInstId != null && !"".equals(procInstId)) {
                actProcessService.deleteProcess(procInstId);
                //插入指定单据流转各环节审批人记录（单据删除记录）
                Map<String, Object> flowRecord = new HashMap<String, Object>();
                flowRecord.put("moduleTable", moduleTable1);
                flowRecord.put("nid", fbaPlanOrder.getNid());
                flowRecord.put("activeFlowOld", "FlowZd");
                flowRecord.put("procInstId", procInstId);
                flowRecord.put("createUser", ShiroUtils.getMandatorId());
                flowRecord.put("createUserName", ShiroUtils.getMandatorName());
                flowRecord.put("updateUsers", "实际删除操作人： " + ShiroUtils.getUserName() + "【" + ShiroUtils.getUserId() + "】");
                flowRecord.put("optType", "delete");
                processInstanceMapper.insertProcessInstanceFlowRecord(flowRecord);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = fbaPlanOrderMapper.selectLastNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = fbaPlanOrderMapper.selectNextNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }

    /**
     * 修改审核状态
     * @return
     * @author DH-Xxj
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateState(Map<String, Object> params) {
        List<FbaPlanOrder> fbaPlanOrderList =  JSON.parseArray(params.get("infoItems").toString(), FbaPlanOrder.class);
        for (FbaPlanOrder item:fbaPlanOrderList
        ) {
            item.setUpdateTime(new Date());
            item.setState(params.get("state").toString());
            item.setAuditTime(new Date());
            item.setAuditUser(ShiroUtils.getUserId());
            fbaPlanOrderMapper.update(item);

            //查询装箱最新数据
            Map<String, Object> params1 = new HashMap<String, Object>();
            params1.put("moduleTable", moduleTable);
            ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params1);    //有事务控制，制单异常不跳过单号
            //新增头程装箱单
            FbaBox fbaBox = new FbaBox();
            fbaBox.setGuid(RandomValueUtils.getGUID());
            fbaBox.setNid(moduleNidAndBid.getNid());
            fbaBox.setBid(moduleNidAndBid.getBid());
            fbaBox.setCid(ShiroUtils.getMandatorCid());
            fbaBox.setCidName(ShiroUtils.getMandatorCidName());
            fbaBox.setbUser(ShiroUtils.getMandatorId());
            fbaBox.setbUserName(ShiroUtils.getMandatorName());
            fbaBox.setbDept(ShiroUtils.getMandatorDeptPath());
            fbaBox.setbDeptName(ShiroUtils.getMandatorDeptName());
            fbaBox.setbPosition(ShiroUtils.getMandatorPositionNameDa());
            fbaBox.setaUser(ShiroUtils.getUserId());
            fbaBox.setaUserName(ShiroUtils.getUserName());
            fbaBox.setaDept(ShiroUtils.getUserDeptPath());
            fbaBox.setaDeptName(ShiroUtils.getUserDeptName());
            fbaBox.setaPosition(ShiroUtils.getUserPositionNameDa());
            fbaBox.setCode(moduleNidAndBid.getBid());
            fbaBox.setState("0");
            fbaBox.setCodeShipment(item.getCode());
            fbaBox.setCreateTime(new Date());
            fbaBox.setUpdateTime(new Date());
            fbaBox.setEffectStock(false);
            fbaBoxMapper.insertFbaBox(fbaBox);

        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }


    /**
     * 查询库存商品库
     * @param params
     * @return List - ProductActive
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<FbaProductActive> queryFbaProductActive(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句


        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.productCode asc";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }

        return fbaPlanOrderMapper.findFbaProductActive(params);
    }

    private void updateNum(FbaPlanOrder fbaPlanOrder,FbaPlanOrderDetail item, Map<String,Object> params,Integer tpye){
        StockControl oldData ;
        StockControl stockControl = new StockControl();
        String operatorName = "";
        if (item.getGuidKc() != null && !item.getGuidKc().equals("")){
            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("rkGuid",item.getRkGuid());
            params2.put("vGsBm",item.getvGsBm());
            params2.put("vHw",item.getCodeStockLocation());
            params2.put("vKq",item.getCodeStockArea());
            params2.put("gDepot",item.getCodeStockOn());
            params2.put("productcode",item.getCommodityCode());
            oldData = storageMapper.findByMultiparameter(params2);
            if (oldData != null) {
                BeanUtils.copyProperties(oldData, stockControl);
                if (tpye == 0) {
                    operatorName = "修改";
                    if (oldData.getProductNum() < item.getNumPlanDeliver()){
                        throw new RuntimeException("商品编码:"+item.getCommodityCode()+"库存数量不足,请核实后再操作!");
                    }
                    //可用数量-计划发货
                    stockControl.setProductNum(oldData.getProductNum() - item.getNumPlanDeliver());
                } else {
                    operatorName = "删除";
                    //可用数量+计划发货
                    stockControl.setProductNum(oldData.getProductNum() + item.getNumPlanDeliver());
                }
                storageMapper.update(stockControl);

                // 新库存添加库存流水
                StockControlRunning stockControlRunning = new StockControlRunning();
                stockControlRunning.setGuid(RandomValueUtils.getGUID());
                stockControlRunning.setGuidStockControl(stockControl.getGuid());
                stockControlRunning.setBidRelative(fbaPlanOrder.getBid());
                stockControlRunning.setLocationHw(item.getCodeStockLocation());
                stockControlRunning.setProductCode(item.getCommodityCode());
                stockControlRunning.setvGsBm(item.getvGsBm());
                stockControlRunning.setCreateTime(new Date());
                if (tpye == 0) {
                    stockControlRunning.setProductNumChange(-item.getNumPlanDeliver());
                    stockControlRunning.setProductNumLeft(oldData.getProductNum() - item.getNumPlanDeliver());
                    stockControlRunning.setRemark("新增头程计划单 - 调出方 " + fbaPlanOrder.getBid());
                } else {
                    stockControlRunning.setProductNumChange(item.getNumPlanDeliver());
                    stockControlRunning.setProductNumLeft(oldData.getProductNum() + item.getNumPlanDeliver());
                    stockControlRunning.setRemark("删除头程计划单 - 调入方 " + fbaPlanOrder.getBid());
                }

                stockControlRunningMapper.insert(stockControlRunning);
                updateLogService.addUpdateLog(params.get("moduleTable").toString(), stockControl.getGuid(), oldData, stockControl, operatorName);
            } else{
                throw new RuntimeException("商品编码:"+item.getCommodityCode()+"库存信息不存在,请核实后再操作!");
            }
        }
    }
}
